package com.isay.frameworklib.widget.exception;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.isay.frameworklib.R;
import com.isay.frameworklib.utils.ViewUtils;

import static com.isay.frameworklib.widget.exception.ExceptionType.EMPTYMESSAGE;
import static com.isay.frameworklib.widget.exception.ExceptionType.IMAGELOADFAIL;
import static com.isay.frameworklib.widget.exception.ExceptionType.LOADING;
import static com.isay.frameworklib.widget.exception.ExceptionType.NETWORKERROR;


/**
 * Created by melody on 2017/3/23.
 * 异常页面提示页面
 */

public class ExceptionalSituationPromptView extends FrameLayout implements View.OnClickListener {


    private ExceptionType mExceptionType = NETWORKERROR;
    private AnimationDrawable mLoadAnim;

    private final String PROMPT_VIEW_TAG = "PROMPT_VIEW";

    private ImageView mPromptImageView;
    private TextView mPromptTextView;
    private View mPromptView;
    private Button mPromptBtn;

    //是否置顶
    private boolean mIsTop = true;
    //提示组件是否已经附加到root
    private boolean mIsAttached = false;

    private int mPromptTextColor = Color.parseColor("#a5a9af");
    private float mPromptTextSize = getResources().getDimensionPixelSize(R.dimen.px28);
    private float mPromptTextPadding = getResources().getDimensionPixelSize(R.dimen.px10);

    private float mPromptImagePaddingTop = 0;
    private float mPromptImagePaddingBottom = 0;

    private float mPromptImageWidth = getResources().getDimensionPixelSize(R.dimen.px300);
    private float mPromptImageHeight = getResources().getDimensionPixelSize(R.dimen.px250);

    private float mLoadingImageWidth = getResources().getDimensionPixelSize(R.dimen.px130);
    private float mLoadingImageHeight = getResources().getDimensionPixelSize(R.dimen.px95);

    private int mPromptType = 0;

    private int mPromptImageSrc = R.drawable.excepion_network_error;

    private String mPromptTextString;
    private String mPromptBtnString;


    public ExceptionalSituationPromptView(Context context) {
        this(context, null);
    }


    public ExceptionalSituationPromptView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(attrs);
    }


    private void initView(AttributeSet attrs) {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        mPromptView = layoutInflater.inflate(R.layout.exception_situation_prompt_view, this, false);
        mPromptView.setTag(PROMPT_VIEW_TAG);
        mPromptImageView = (ImageView) mPromptView.findViewById(R.id.prompt_image);
        mPromptTextView = (TextView) mPromptView.findViewById(R.id.prompt_text);
        mPromptBtn = (Button) mPromptView.findViewById(R.id.prompt_btn);
        mPromptBtn.setOnClickListener(this);

        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ExceptionalSituationPromptView);
        mPromptTextColor = typedArray.getColor(R.styleable.ExceptionalSituationPromptView_promptTextColor, mPromptTextColor);
        mPromptTextSize = typedArray.getDimension(R.styleable.ExceptionalSituationPromptView_promptTextSize, mPromptTextSize);
        mPromptTextPadding = typedArray.getDimension(R.styleable.ExceptionalSituationPromptView_promptTextPadding, mPromptTextPadding);

        mPromptImagePaddingTop = typedArray.getDimension(R.styleable.ExceptionalSituationPromptView_promptImagePaddingTop, mPromptImagePaddingTop);
        mPromptImagePaddingBottom = typedArray.getDimension(R.styleable.ExceptionalSituationPromptView_promptImagePaddingBottom, mPromptImagePaddingBottom);
        mPromptImageWidth = typedArray.getDimension(R.styleable.ExceptionalSituationPromptView_promptImagePaddingBottom, mPromptImageWidth);
        mPromptImageHeight = typedArray.getDimension(R.styleable.ExceptionalSituationPromptView_promptImagePaddingBottom, mPromptImageHeight);
        mPromptType = typedArray.getInt(R.styleable.ExceptionalSituationPromptView_promptType, mPromptType);
        //文字
        mPromptTextString = typedArray.getString(R.styleable.ExceptionalSituationPromptView_promptTextString);
        mPromptBtnString = typedArray.getString(R.styleable.ExceptionalSituationPromptView_promptBtnString);
        mPromptImageSrc = typedArray.getResourceId(R.styleable.ExceptionalSituationPromptView_promptImageSrc, mPromptImageSrc);
        typedArray.recycle();

        mPromptTextView.setTextColor(mPromptTextColor);
        mPromptTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) mPromptTextSize);
        mPromptTextView.setPadding((int) mPromptTextPadding, (int) mPromptTextPadding, (int) mPromptTextPadding, (int) mPromptTextPadding);
        mPromptImageView.setPadding(0, (int) mPromptImagePaddingTop, 0, (int) mPromptImagePaddingBottom);

        setExceptionViewParams();
        //自定义图片  与指定类型互斥  有自定义图片文字 类型将失效
        if (TextUtils.isEmpty(mPromptTextString)) {
            getType();
        } else {
            ViewUtils.setImageViewSrc(getContext(), mPromptImageView, mPromptImageSrc);
            mPromptTextView.setText(mPromptTextString);
        }
        if (!TextUtils.isEmpty(mPromptBtnString)) {
            mPromptBtn.setText(mPromptBtnString);
            mPromptBtn.setVisibility(View.VISIBLE);
        } else {
            mPromptBtn.setVisibility(View.GONE);
        }
    }

    public Button getPromptBtn() {
        return mPromptBtn;
    }

    private void getType() {
        if (NETWORKERROR.getValue() == mPromptType) {
            mExceptionType = NETWORKERROR;
        } else if (EMPTYMESSAGE.getValue() == mPromptType) {
            mExceptionType = EMPTYMESSAGE;
        } else if (IMAGELOADFAIL.getValue() == mPromptType) {
            mExceptionType = IMAGELOADFAIL;
        } else if (LOADING.getValue() == mPromptType) {
            mExceptionType = LOADING;
        }
        setDefaultData();
    }

    /**
     * 选择默认样式
     */
    private void setDefaultData() {
        PromptModel model = new PromptModel();
        int imgSrc = R.drawable.excepion_network_error;
        String promptText = getResources().getString(R.string.exception_network_error);
        String promptBtnText = getResources().getString(R.string.exception_btn_text);
        switch (mExceptionType) {
            case NETWORKERROR:
                promptText = getResources().getString(R.string.exception_network_error);
                imgSrc = R.drawable.excepion_network_error;
                model.setPromptBtnString(promptBtnText);
                break;
            case EMPTYMESSAGE:
                promptText = getResources().getString(R.string.exception_empty_message);
                imgSrc = R.drawable.excepion_empty_message;
                break;
            case IMAGELOADFAIL:
                promptText = getResources().getString(R.string.exception_imageload_fail);
                imgSrc = R.drawable.exception_imageload_fail;
                break;
            case LOADING:
                promptText = getResources().getString(R.string.exception_loading);
                imgSrc = R.drawable.anim_loading;
                break;
        }
        model.setImgSrcId(imgSrc);
        model.setPromptString(promptText);
        setPromptViewData(model);
    }

    private void setExceptionViewParams() {
        ViewGroup.LayoutParams layoutParams = mPromptImageView.getLayoutParams();
        layoutParams.height = (int) mPromptImageHeight;
        layoutParams.width = (int) mPromptImageWidth;
        mPromptImageView.setLayoutParams(layoutParams);
    }

    /**
     * 设置默认样式
     *
     * @param type
     */
    public void setExceptionType(ExceptionType type) {
        this.mExceptionType = type;
        //重置样式
        setDefaultData();
    }

    /**
     * 设置数据
     * 默认是透明背景，当LOADING 样式时候背景为白色
     *
     * @param model
     */
    public void setPromptViewData(PromptModel model) {
        if (model.getImgSrcId() == R.drawable.anim_loading && mExceptionType == LOADING) {
            mPromptImageView.setImageResource(R.drawable.anim_loading);
            mPromptView.setBackgroundColor(Color.WHITE);
            ViewGroup.LayoutParams params = mPromptImageView.getLayoutParams();
            params.height = (int) mLoadingImageHeight;
            params.width = (int) mLoadingImageWidth;
            mPromptImageView.setLayoutParams(params);
        } else {
            setExceptionViewParams();
            mLoadAnim = null;
            mPromptView.setBackgroundColor(Color.TRANSPARENT);
            ViewUtils.setImageViewSrc(getContext(), mPromptImageView, model.getImgSrcId());
        }
        if (!TextUtils.isEmpty(model.getPromptString()) && mPromptTextView != null)
            mPromptTextView.setText(model.getPromptString());
        if (!TextUtils.isEmpty(model.getPromptBtnString())) {
            mPromptBtn.setVisibility(View.VISIBLE);
            mPromptBtn.setText(model.getPromptBtnString());
        } else {
            mPromptBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 设置提示文字
     *
     * @param proptText
     */
    public void setPromptText(String proptText) {
        if (!TextUtils.isEmpty(proptText) && mPromptTextView != null) {
            mPromptTextView.setText(proptText);
        }
    }

    /**
     * 设置提示文字
     */
    public void setPromptText(int resId) {
        if (mPromptTextView != null) {
            if (resId != 0) {
                mPromptTextView.setText(resId);
            } else {
                mPromptTextView.setText(null);
            }
        }
    }


    /**
     * 设置提示文字颜色
     *
     * @param color
     */
    public void setPromptTextColor(int color) {
        if (mPromptTextView != null)
            mPromptTextView.setTextColor(color);
    }

    /**
     * 设置提示文字大小
     *
     * @param size
     */
    public void setPromptTextSize(int size) {
        if (mPromptTextView != null)
            mPromptTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
    }


    /**
     * 设置提示文字 padding
     *
     * @param padding
     */
    public void setPromptTextPadding(int padding) {
        if (mPromptTextView != null)
            mPromptTextView.setPadding(padding, padding, padding, padding);
    }

    /**
     * 设置提示图片 大小
     *
     * @param width
     * @param height
     */
    public void setPromptImageSize(int width, int height) {
        if (mPromptImageView != null) {
            ViewGroup.LayoutParams params = mPromptImageView.getLayoutParams();
            params.height = height;
            params.width = width;
            mPromptImageView.setLayoutParams(params);
        }
    }

    /**
     * 设置提示图片 padding
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setPromptImagePadding(int left, int top, int right, int bottom) {
        if (mPromptImageView != null)
            mPromptImageView.setPadding(left, top, right, bottom);
    }

    public void setPromptImageMargin(int left, int top, int right, int bottom) {
        if (mPromptImageView != null) {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mPromptImageView.getLayoutParams();
            if (null != params) {
                params.setMargins(left, top, right, bottom);
            }
        }
    }

    /**
     * 设置提示图片
     *
     * @param src
     */
    public void setPromptImageSource(int src) {
        if (mPromptImageView != null) {
//            mPromptImageView.setImageResource(src);
            ViewUtils.setImageViewSrc(getContext(), mPromptImageView, src);
            if (mExceptionType == LOADING) {
                mExceptionType = null;
            }
        }
    }

    public ImageView getPromptImageView() {
        return mPromptImageView;
    }

    /**
     * 设置提示图片
     *
     * @param bitMap
     */
    public void setPromptImageBitmap(Bitmap bitMap) {
        if (bitMap != null && mPromptImageView != null) {
            mPromptImageView.setImageBitmap(bitMap);
            if (mExceptionType == LOADING) {
                mExceptionType = null;
            }
        }

    }

    /**
     * 设置提示图片
     *
     * @param drawable
     */
    public void setPromptImageDrawable(Drawable drawable) {
        if (drawable != null && mPromptImageView != null) {
            mPromptImageView.setImageDrawable(drawable);
            if (mExceptionType == LOADING) {
                mExceptionType = null;
            }
        }
    }


    /**
     * 设置按钮文字
     *
     * @param str
     */
    public void setPromptBtnText(String str) {
        if (!TextUtils.isEmpty(str)) {
            mPromptBtn.setText(str);
        }
    }

    /**
     * 显示提示内容
     */
    public void show() {
        dismiss();
        if (mPromptView != null) {
            setPromptViewVisibility(View.VISIBLE);
        }
    }

    public void show(ExceptionType exceptionType) {
        dismiss();
        if (mPromptView != null) {
            this.mExceptionType = exceptionType;
            setDefaultData();
            setPromptViewVisibility(View.VISIBLE);
        }

    }

    public void show(String promptString, int imgSrc) {
        dismiss();
        if (mPromptView != null) {
            if (!TextUtils.isEmpty(promptString))
                setPromptViewData(new PromptModel(imgSrc, promptString));
            setPromptViewVisibility(View.VISIBLE);
        }
    }

    public void show(String promptString, int imgSrc, String btnPrompt, OnPromptClickListener l) {
        dismiss();
        if (mPromptView != null) {
            if (!TextUtils.isEmpty(promptString))
                setPromptViewData(new PromptModel(imgSrc, promptString));
            if (!TextUtils.isEmpty(btnPrompt)) {
                mPromptBtn.setText(btnPrompt);
                mPromptBtn.setVisibility(View.VISIBLE);
                this.mOnPromptClickListener = l;
                //设置点击事件 ，必须处于顶层
                setPromptViewTop(true);
            }
            setPromptViewVisibility(View.VISIBLE);
        }

    }

    public void show(String promptString, int imgSrc, String btnPrompt) {
        dismiss();
        if (mPromptView != null) {
            if (!TextUtils.isEmpty(promptString))
                setPromptViewData(new PromptModel(imgSrc, promptString));
            if (!TextUtils.isEmpty(btnPrompt)) {
                mPromptBtn.setText(btnPrompt);
                mPromptBtn.setVisibility(View.VISIBLE);
                //设置点击事件 ，必须处于顶层
                setPromptViewTop(true);
            }
            setPromptViewVisibility(View.VISIBLE);
        }

    }

    /**
     * 隐藏提示内容
     */
    public void dismiss() {
        if (mPromptView != null) {
            setPromptViewVisibility(View.GONE);
        }
        if (mLoadAnim != null && mLoadAnim.isRunning()) {
            mLoadAnim.stop();
            mLoadAnim = null;
        }
    }

    private void setPromptViewVisibility(int visibility) {
        if (visibility == View.VISIBLE) {
            setPromptViewTop(mIsTop);
        }
        mPromptView.setVisibility(visibility);
        if (mExceptionType == LOADING) {
            startLoading();
        }
    }

    private void startLoading() {
        Drawable drawable = mPromptImageView.getDrawable();
        if (drawable instanceof AnimationDrawable) {
            mLoadAnim = (AnimationDrawable) drawable;
            if (mLoadAnim != null) {
                mLoadAnim.start();
            }
        }
    }


    @Override
    public void onClick(View view) {
        if (view == mPromptBtn) {
            if (mOnPromptClickListener != null)
                mOnPromptClickListener.promptClick();
        }
    }


    public interface OnPromptClickListener {
        void promptClick();
    }

    private OnPromptClickListener mOnPromptClickListener;

    /**
     * 设置点击刷新监听
     *
     * @param l
     */
    public void setOnClickRefreshListener(OnPromptClickListener l) {
        this.mOnPromptClickListener = l;
        //设置点击事件 ，必须处于顶层
        setPromptViewTop(true);
    }

    /**
     * 设置PromptView 是否置于顶层 默认处于底层
     * 设置顶层可以触发点击事件
     *
     * @param isTop
     */
    public void setPromptViewTop(boolean isTop) {
        //已附加且置顶状态相同则不做处理
        if (mIsAttached && isTop == mIsTop) {
            return;
        }
        mIsTop = isTop;
        if (this.getChildCount() > 0 && mPromptView != null) {
            this.removeView(mPromptView);
            if (!isTop && mOnPromptClickListener == null) {
                mIsTop = false;
                this.addView(mPromptView, 0);
            } else {
                if (this.getChildCount() > 0) {
                    this.addView(mPromptView, this.getChildCount());
                } else {
                    this.addView(mPromptView);
                }
                mIsTop = true;
            }
        } else {
            this.addView(mPromptView);
            mIsTop = true;
        }

    }

    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        if (child.getTag() != null && child.getTag().equals(PROMPT_VIEW_TAG)) {
            mIsAttached = true;
        }
    }

    public class PromptModel {
        public PromptModel() {
        }

        public PromptModel(int imgSrcId, String promptString) {
            this.imgSrcId = imgSrcId;
            this.promptString = promptString;
        }

        public PromptModel(int imgSrcId, String promptString, String promptBtnString) {
            this.imgSrcId = imgSrcId;
            this.promptString = promptString;
            this.promptBtnString = promptBtnString;
        }

        //图片
        private int imgSrcId;
        //文字
        private String promptString;
        //按钮文字
        private String promptBtnString;

        public String getPromptBtnString() {
            return promptBtnString;
        }

        public void setPromptBtnString(String promptBtnString) {
            this.promptBtnString = promptBtnString;
        }

        public int getImgSrcId() {
            return imgSrcId;
        }

        public void setImgSrcId(int imgSrcId) {
            this.imgSrcId = imgSrcId;
        }

        public String getPromptString() {
            return promptString;
        }

        public void setPromptString(String promptString) {
            this.promptString = promptString;
        }
    }


    public boolean isPromptViewShown() {
        return mPromptView != null && mPromptView.isShown();
    }

    public boolean isLoading() {
        return isPromptViewShown() && mLoadAnim != null && mLoadAnim.isRunning();
    }
}
